package com.javaketang.dky.fileter;


import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@WebFilter(filterName = "userSession",urlPatterns = {"/*"})
public class UserLoginFilter implements Filter {

    private static List<String> urls = Arrays.asList(new String[]{"product","user","upload","regist","images","js","css","initIndex","statics/*", "index", "login","log"});


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {


        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse rep = (HttpServletResponse) servletResponse;
        HttpSession session = req.getSession();

        //获取当前请求的url
        String uri = req.getRequestURI();

//        System.out.println("请求路径--》》"+uri);
//
//        System.out.println("session--->>>>"+session.getAttribute("userSession"));

        String path=req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+req.getContextPath();

        if (isIegalUrl(uri)) {

            //放行
            chain.doFilter(servletRequest, servletResponse);
        } else {

          if(session!=null&&session.getAttribute("userSession") != null){

                chain.doFilter(servletRequest,servletResponse);

            }else{

              rep.sendRedirect(path+"/user/initIndex");
            }

        }


    }

    @Override
    public void destroy() {

    }


    private boolean isIegalUrl(String uri) {
        for (String string : urls) {
            //如果当前请求包括这些静态资源文件，则不处理，
            if (uri.indexOf(string) > -1) {
                return true;
            }
        }

        return false;
    }

}
